package com.example.goodpet.home.fragment;

import android.Manifest;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.viewpager2.widget.ViewPager2;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.example.goodpet.R;
import com.example.goodpet.activity.SearchActivity;
import com.example.goodpet.base.BaseFragment;
import com.example.goodpet.home.adapter.HomePagerAdapter;
import com.example.goodpet.home.homeFocus.fragment.HomeFocusFragment;
import com.example.goodpet.home.homeRecommend.fragment.HomeRecommendFragment;
import com.example.goodpet.utils.MyApplication;
import com.example.goodpet.utils.UIUtils;
import com.github.gzuliyujiang.dialog.DialogColor;
import com.github.gzuliyujiang.dialog.DialogConfig;
import com.github.gzuliyujiang.dialog.DialogStyle;
import com.github.gzuliyujiang.wheelpicker.AddressPicker;
import com.github.gzuliyujiang.wheelpicker.annotation.AddressMode;
import com.github.gzuliyujiang.wheelpicker.contract.OnAddressPickedListener;
import com.github.gzuliyujiang.wheelpicker.entity.CityEntity;
import com.github.gzuliyujiang.wheelpicker.entity.CountyEntity;
import com.github.gzuliyujiang.wheelpicker.entity.ProvinceEntity;

import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;

public class HomeFragment extends BaseFragment{

    private static final String TAG = HomeFragment.class.getSimpleName();

    private RadioGroup rgTop;
    private TextView tv_search_home;
    private TextView tv_share_home;
    private TextView tv_app_name;
    private ViewPager2 viewpager;
    private RadioButton rbHomeLocation;

    private HomePagerAdapter adapter;
    /**
     * 初始化主页面Fragment的UI
     */
    @Override
    public View initView() {

//        Log.e(TAG, "initView: 主页视图初始化了");
        View view = View.inflate(mContext, R.layout.fragment_home, null);
        rbHomeLocation = view.findViewById(R.id.home_top_rb_location);
        tv_search_home = view.findViewById(R.id.tv_search_home);
        tv_share_home = view.findViewById(R.id.tv_share_home);
        rgTop=view.findViewById(R.id.home_top_rg);
        viewpager = view.findViewById(R.id.vp_home);
        tv_app_name = view.findViewById(R.id.tv_app_name);
        //修改字体
        Typeface typeFace = Typeface.createFromAsset(getActivity().getAssets(), "fonts/QianTuXiaoTuTi-2.ttf");
        // 应用字体
        tv_app_name.setTypeface(typeFace);

        return view;
    }

    @Override
    public void initData() {
        super.initData();
        //申请定位权限，申请成功后自动进行定位
        methodRequiresTwoPermission();
        //初始化Home适配器，添加fragment进适配器
        initAdapter();
        //设置点击事件
        initListener();
    }

    /**
     * 初始化Home适配器，添加fragment进适配器
     */
    private void initAdapter() {
        adapter = new HomePagerAdapter(this);
        adapter.addFragment(new HomeFocusFragment());
        adapter.addFragment(new HomeRecommendFragment());
//        adapter.addFragment(new HomeLocationFragment());
        viewpager.setAdapter(adapter);
        viewpager.setCurrentItem(1);
        rgTop.check(R.id.home_top_rb_recommend);
    }

    //声明AMapLocationClient类对象
    public AMapLocationClient mLocationClient = null;
    //声明定位回调监听器
    public AMapLocationListener mLocationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation aMapLocation) {
            if (aMapLocation != null) {
                if (aMapLocation.getErrorCode() == 0) {

                    //可在其中解析amapLocation获取相应内容。
                    if(null!=aMapLocation.getCity()){
                        rbHomeLocation.setText(aMapLocation.getCity());
                        MyApplication.location=aMapLocation.getCity();
                        MyApplication.locationId=aMapLocation.getCity();
                        MyApplication.locationSpecific=aMapLocation.getCity();
                        Log.e(TAG, "onLocationChanged: "+MyApplication.location );
                    }else{
                        if(null!=aMapLocation.getAddress()){
                            MyApplication.locationSpecific=aMapLocation.getAddress();
                        }
                        MyApplication.location=aMapLocation.getProvince();
                        MyApplication.locationId=aMapLocation.getProvince();
                        MyApplication.locationSpecific=aMapLocation.getProvince();
                        rbHomeLocation.setText(aMapLocation.getProvince());
                    }
                    MyApplication.longitude=aMapLocation.getLongitude();
                    MyApplication.latitude=aMapLocation.getLatitude();
                    initAdapter();
                }else {
                    //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
                    Log.e("AmapError","location Error, ErrCode:"
                            + aMapLocation.getErrorCode() + ", errInfo:"
                            + aMapLocation.getErrorInfo());
                    UIUtils.toast("定位失败",false);
                    mLocationClient.stopLocation();//停止定位后，本地定位服务并不会被销毁
//                    mLocationClient.onDestroy();//销毁定位客户端，同时销毁本地定位服务。
                }
            }
        }
    };
    //声明AMapLocationClientOption对象
    public AMapLocationClientOption mLocationOption = null;

    //动态申请权限
    @AfterPermissionGranted(0)
    private void methodRequiresTwoPermission() {
        String[] perms = {Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION,
                /*Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE*//*,
                Manifest.permission.READ_PHONE_STATE*/};

        if (EasyPermissions.hasPermissions(getContext(), perms)) {
            // Already have permission, do the thing
            // ...
            initLocation();
        } else {
            // Do not have permissions, request them now
            EasyPermissions.requestPermissions(this, getString(R.string.location_rationale),
                    0, perms);
//            methodRequiresTwoPermission();
        }
    }

    private void initLocation() {

        //初始化定位
        try {
            mLocationClient = new AMapLocationClient(getContext());
        } catch (Exception e) {
            e.printStackTrace();
        }
        //设置定位回调监听
        mLocationClient.setLocationListener(mLocationListener);
        //初始化AMapLocationClientOption对象
        mLocationOption = new AMapLocationClientOption();

        AMapLocationClientOption option = new AMapLocationClientOption();
        /**
         * 设置定位场景，目前支持三种场景（签到、出行、运动，默认无场景）
         */
        option.setLocationPurpose(AMapLocationClientOption.AMapLocationPurpose.SignIn);
        if(null != mLocationClient){
            mLocationClient.setLocationOption(option);
            //设置场景模式后最好调用一次stop，再调用start以保证场景模式生效
            mLocationClient.stopLocation();
            mLocationClient.startLocation();
        }
        //设置定位模式为AMapLocationMode.Battery_Saving，低功耗模式。
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Battery_Saving);
        //获取一次定位结果：
        //该方法默认为false。
        mLocationOption.setOnceLocation(true);
        //获取最近3s内精度最高的一次定位结果：
        //设置setOnceLocationLatest(boolean b)接口为true，启动定位时SDK会返回最近3s内精度最高的一次定位结果。如果设置其为true，setOnceLocation(boolean b)接口也会被设置为true，反之不会，默认为false。
        mLocationOption.setOnceLocationLatest(true);
        mLocationOption.setOnceLocationLatest(true);

        //设置是否返回地址信息（默认返回地址信息）
//        mLocationOption.setNeedAddress(true);
        //设置是否允许模拟位置,默认为true，允许模拟位置
//        mLocationOption.setMockEnable(true);
        //单位是毫秒，默认30000毫秒，建议超时时间不要低于8000毫秒。
        mLocationOption.setHttpTimeOut(20000);
        //关闭缓存机制
//        mLocationOption.setLocationCacheEnable(false);
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        //启动定位
        mLocationClient.startLocation();
    }

    private void initListener() {

        rgTop.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.home_top_rb_focus:
                        //adapter.notify();
                        viewpager.setCurrentItem(0);
                        //viewpager.setAdapter();
                        break;
                    case R.id.home_top_rb_recommend:
                        viewpager.setCurrentItem(1);
                        break;
//                    case R.id.home_top_rb_location:
//                        viewpager.setCurrentItem(2);
//                        break;
                }

            }
        });

        rbHomeLocation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DialogConfig.setDialogStyle(DialogStyle.Three);
                DialogConfig.setDialogColor(new DialogColor()
                        .cancelTextColor(0xFF999999)
                        .okTextColor(0xFF0099CC));

                AddressPicker picker = new AddressPicker(getActivity());
                picker.setAddressMode(AddressMode.PROVINCE_CITY);

                picker.setOnAddressPickedListener(new OnAddressPickedListener() {
                    @Override
                    public void onAddressPicked(ProvinceEntity province, CityEntity city, CountyEntity county) {
                        if(null!=city){
                            rbHomeLocation.setText(city.getName());
                            MyApplication.location=city.getName();
                            MyApplication.locationId=city.getCode();
                            MyApplication.locationSpecific=city.getName();
                        }else{
                            if(null!=county){
                                MyApplication.locationSpecific=county.getName();
                            }
                            MyApplication.locationSpecific=province.getName();
                            rbHomeLocation.setText(province.getName());
                            MyApplication.location=city.getName();
                            MyApplication.locationId=city.getCode();
                        }
                        initAdapter();

                    }
                });
                picker.show();

            }
        });

        viewpager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                switch (position) {
                    case 0:
                        ((RadioButton) rgTop.findViewById(R.id.home_top_rb_focus)).setChecked(true);
                        break;
                    case 1:
                        ((RadioButton) rgTop.findViewById(R.id.home_top_rb_recommend)).setChecked(true);
                        break;
//                    case 2:
//                        ((RadioButton) rgTop.findViewById(R.id.home_top_rb_location)).setChecked(true);
//                        break;
                }
            }
        });



        //搜素的监听
        tv_search_home.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(mContext,SearchActivity.class);
                intent.putExtra("type",1);
                mContext.startActivity(intent);

//                Toast.makeText(mContext, "搜索", Toast.LENGTH_SHORT).show();
            }
        });

        //分享的监听
        tv_share_home.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(mContext, "进入分享页面", Toast.LENGTH_SHORT).show();
            }
        });

    }
}
